package action;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * Servlet implementation class PayApiServlet
 */
public class PayApiByServiceServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public PayApiByServiceServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String jsonStr = request.getReader().readLine();
		List<JSONObject> list = JSON.parseArray(jsonStr, JSONObject.class);
		
		// 订单ID
		String oid = "";
		if(list.get(0).getString("rdealId")!=null && list.get(0).getString("rdealId").trim()!=""){
			oid = list.get(0).getString("rdealId");
		}
		// 订单编号
		String number = "";
		if(list.get(0).getString("rdealNumber")!=null && list.get(0).getString("rdealNumber").trim()!=""){
			number = list.get(0).getString("rdealNumber");
		}
		
		// 订单创建时间
		String createTime = "";
		if(list.get(0).getString("rdealAffirmTime")!=null && list.get(0).getString("rdealAffirmTime").trim()!=""){
			createTime = list.get(0).getString("rdealAffirmTime");
		}
		// 实际支付价格
		String payment = "";
		if(list.get(0).getString("rdealBuyPrice")!=null && list.get(0).getString("rdealBuyPrice").trim()!=""){
			payment = list.get(0).getString("rdealBuyPrice");
		}
		// 订单状态
		String status = "";
		if(list.get(0).getString("rdealPayStatus")!=null && list.get(0).getString("rdealPayStatus").trim()!=""){
			status = list.get(0).getString("rdealPayStatus");
		}
		// 成果名称
		String infoName = "";
		if(list.get(1).getString("infoname")!=null && list.get(1).getString("infoname").trim()!=""){
			infoName = list.get(1).getString("infoname");
		}
		// 备注
		String ordermessage = "";
//		if(list.get(0).getString("message")!=null && list.get(0).getString("message").trim()!=""){
//			ordermessage = list.get(0).getString("message");
//		}
		
		String parentMerchantNo = YeepayService.getParentMerchantNo();
		String merchantNo = YeepayService.getMerchantNo();
		//订单编号、商户订单号
		/*String orderId = request.getParameter("orderId");*/
		String orderId = number;
		//订单价格
		/*String orderAmount = request.getParameter("orderAmount");*/
		String orderAmount = payment;
		//订单有效期
		/*String timeoutExpress = request.getParameter("timeoutExpress");*/
		String timeoutExpress = 12*60 + "";
		//请求时间
		/*String requestDate = request.getParameter("requestDate");*/
		String requestDate = createTime;
		//回调地址
		/*String redirectUrl = request.getParameter("redirectUrl");*/
		//Instrument/new_file3_2?serviceId=64&soid=2250&display=true
		String redirectUrl = "http://222.76.204.85:20501/Scientific/orderManagement37";
		//服务器回调地址，支付成功回调地址
		/*String notifyUrl = request.getParameter("notifyUrl");*/
		String notifyUrl = "http://222.76.204.85:20501/Scientific/PayBackpostbyservice";
		//商品名称
		/*String goodsName = request.getParameter("goodsName");*/
		String goodsName = infoName;
		//商品描述
		/*String goodsDesc = request.getParameter("goodsDesc");*/
		String goodsDesc = ordermessage;
		
		String paymentParamExt = "";
		String industryParamExt = "";
		String memo = "";
		String riskParamExt = "";
		String csUrl = "";
		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Date d = new Date();
		try {
			d = f.parse(createTime);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String timestamp = d.getTime()/1000 + "";
		String directPayType = "";
		String cardType = "";
		String userNo = "100100010000";
		String userType = "IMEI";
		String appId = "";
		String openId = "";
		String clientId = "";

		String goodsParamExt = "{\"goodsName\":\"" + goodsName + "\",\"goodsDesc\":\"" + goodsDesc + "\"}";
		String ext = "{\"appId\":\"" + appId + "\",\"openId\":\"" + openId + "\",\"clientId\":\"" + clientId + "\"}";

		Map<String, String> params = new HashMap<>();
		params.put("parentMerchantNo", parentMerchantNo);
		params.put("merchantNo", merchantNo);
		params.put("orderId", orderId);
		params.put("orderAmount", orderAmount);
		params.put("timeoutExpress", timeoutExpress);
		params.put("requestDate", requestDate);
		params.put("redirectUrl", redirectUrl);
		params.put("notifyUrl", notifyUrl);
		params.put("goodsParamExt", goodsParamExt);
		params.put("paymentParamExt", paymentParamExt);
		params.put("industryParamExt", industryParamExt);
		params.put("memo", memo);
		params.put("riskParamExt", riskParamExt);
		params.put("csUrl", csUrl);

		Map<String, String> result = new HashMap<>();
		String uri = YeepayService.getUrl(YeepayService.TRADEORDER_URL);
		result = YeepayService.requestYOP(params, uri, YeepayService.TRADEORDER, YeepayService.TRADEORDER_HMAC);

		String token = result.get("token");
		String codeRe = result.get("code");
		if (!"OPR00000".equals(codeRe)) {
			String message = result.get("message");
			response.getWriter().write(message);
		}
		params.put("parentMerchantNo", parentMerchantNo);
		params.put("merchantNo", parentMerchantNo);
		params.put("token", token);
		params.put("timestamp", timestamp);
		params.put("directPayType", directPayType);
		params.put("cardType", cardType);
		params.put("userNo", userNo);
		params.put("userType", userType);
		params.put("ext", ext);
		String url = YeepayService.getUrl(params);
		System.out.println(url); 
		PrintWriter writer = response.getWriter();
		writer.print(url);
		writer.flush();
	}
}
